package com.zero.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * web相关的配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 注册解决跨域的过滤器组件
     * @return
     */
    @Bean
    public CorsFilter crosFilter(){
        //创建跨域配置对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        //添加允许任何跨域请求的配置
        corsConfiguration.addAllowedOrigin("*");

        //添加允许任何请求头部的配置
        corsConfiguration.addAllowedHeader("*");

        //添加允许任何请求方法的配置
        corsConfiguration.addAllowedMethod("*");

        //创建基于url请求的跨域配置源
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();

        //设置跨域配置源拦截所有的请求（"/**"），并加载跨域配置对象
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        //使用跨域配置源创建过滤器，并返回
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

    /**
     * 将拦截器注册到容器中
     * @return
     */
    @Bean
    public TokenInterceptor tokenInterceptor(){
        return new TokenInterceptor();
    }

    /**
     * 在web中注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截除了登录以外的请求
        registry.addInterceptor(tokenInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/register", "/email/feedbackImg");
    }
}
